package edu.hit;

import edu.hit.RESP.RespData;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;

/*
Redis generally uses RESP as a request-response protocol in the following way:

-   Clients send commands to a Redis server as an array of bulk strings.
    The first (and sometimes also the second) bulk string in the array is the command's name.
    Subsequent elements of the array are the arguments for the command.

-   The server replies with a RESP type.
    The reply's type is determined by the command's implementation and possibly by the client's protocol version.
 */

public class Protocol {



    public static final byte DOLLAR_BYTE = '$';
    public static final byte ASTERISK_BYTE = '*';
    public static final byte PLUS_BYTE = '+';
    public static final byte MINUS_BYTE = '-';
    public static final byte COLON_BYTE = ':';

    private Protocol(){
        //确保不能被实例化
    }

    public static void sendCommand(){

    }

    public static String process(BufferedReader reader) throws Exception {

        final char c = (char) reader.read();
        return switch (c){
            case '$' -> processBulkString(reader);
            case '*' -> processArrayBulkString(reader);
            case '\uFFFF' -> null;
            default -> throw new RuntimeException("unkonwn character");
        };


                



    }

    private static void processError(InputStream is) {
    }

    private static RespData processInteger(InputStream is) {
        return null;
    }

    // *2\r\n
    // $4\r\n
    // echo\r\n
    // $3\r\n
    // hey\r\n -->  echo hey
    private static String processArrayBulkString(BufferedReader reader) throws Exception {
        int size = Character.getNumericValue(reader.readLine().charAt(0));
        StringBuilder sb = new StringBuilder();
        for (int i =0;i<size ;i++){
            sb.append(process(reader));
            sb.append(" ");
        }

        return sb.toString();


    }

    // $5\r\n
    // hello\r\n --> hello
    private static String processBulkString(BufferedReader reader) throws IOException {
        reader.readLine();

        return reader.readLine();
    }

    //+OK\r\n --> OK
    private static RespData processSimpleString(InputStream is) throws IOException {
        return null;
    }
}

